package jgcp.master.network;

import java.util.List;

import jgcp.config.Configuration;
import jgcp.master.service.MasterService;
import jgcp.message.Message;
import jgcp.message.MessageType;
/**
 * 
 * @Date 31/05/2009
 * @author Jie Zhao (288654)
 * @version 1.0
 */
public class ErrorDetector extends Thread {
	public ErrorDetector() {
		setDaemon(true);
	}

	public void run() {
		System.out.println("Communication Error Detection Thread Started.");
		Message m = new Message();
		m.setType(MessageType.HEARTBEAT);
		m.setMessageBody("");
		MasterService ms = new MasterService();
		WorkerList workers = WorkerList.getInstance();
		while (true) {
			List<Integer> wl = WorkerList.getInstance().getWorkerList();
			for (Integer i : wl) {
				try {
					ms.sendMessage(i, m);
				} catch (Exception e) {
					workers.removeWorker(i);
				}
			}

			try {
				Thread
						.sleep(Configuration.getInstance()
								.getHeartbeatInterval());
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
